/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * OrderUI.java
 *
 * Created on 29-Mar-2011, 11:42:55
 */
package View;

import Controller.IFSalesOrderController;
import Controller.SalesOrderController;
import DB.IFStatusManager;
import Model.Customer;
import Model.Item;
import Model.Product;
import Model.SalesOrder;
import Model.Status;
import Model.Type;
import Model.ZipCode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

/**
 *
 * @author kostas
 */
public class OrderUI extends javax.swing.JFrame {

    private SalesOrder order;
    private Customer customer;
    private boolean customerSelected = false;
    private boolean orderSelected = false;
    private ArrayList<Item> items;
    private StatusDataModel statusDataModel;
    private ItemTableModel itemTableModel;
    private IFSalesOrderController controller;
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATEFORMAT);
    private ArrayList<Status> statuses;
    private static final String EMPTYSTRING = "";
    private static final String DATEFORMAT = "dd/MM/yyyy";
    private static final String ORDERID_TITLE = "Order ID:";
    private static final String ITEMID_TITLE = "Item ID:";
    private static final String CUSTOMERID_TITLE = "Customer ID:";
    private static final String NOT_A_NUMBER = "Field is either empty or not a number!";
    private static final String ORDER_DOES_NOT_EXIST = "Order with specified ID does not exist.";
    private static final String CUSTOMER_DOES_NOT_EXIST = "Customer with specified ID does not exist.";
    private static final String ITEM_DOES_NOT_EXIST = "Item with specified ID does not exist.";
    private static final String SELECT_CUSTOMER = "Select customer";
    private static final String DESELECT_CUSTOMER = "Deselect customer";
    private static final String SELECT_ORDER = "Select order";
    private static final String DESELECT_ORDER = "Deselect order";
    private static final String ORDER_CREATED = "Order was successfully created.";
    private static final String ORDER_NOT_COMPLETE = "Order is not complete. Please verify that you have filled the following information:\n"
            + "- Selected a customer\n"
            + "- Added at least one item\n"
            + "- Picked a delivery date";
    private static final String NO_ITEM_SELECTED = "At first select an item in the table you want to remove.";
    private static final String STATUSES_TITLE = "Statuses";
    private static final String STATUSES_DOES_NOT_EXIST = "There was an error retrieving delivery statuses from database.\n"
            + "Please contact your system administrator!";

    /** Creates new form OrderUI */
    public OrderUI() {
        try {
            controller = new SalesOrderController();
            statuses = controller.getStatuses(IFStatusManager.SALESORDER);
//            statuses = returnDummyStatuses();
            statusDataModel = new StatusDataModel(statuses);
            itemTableModel = new ItemTableModel(new ArrayList<Item>());
            initComponents();
            if (order != null) {
                totalPriceTextField.setText(String.valueOf(order.getTotalPrice()));
            } else {
                calculateTotalPrice();
            }
            deliveryStatusDropBox.setModel(statusDataModel);
            deliveryStatusDropBox.setSelectedIndex(0);
            itemTable.setModel(itemTableModel);
        } catch (IllegalArgumentException ex) {
            // If delivery statuses do not exist in the database
            showDialog(STATUSES_TITLE, STATUSES_DOES_NOT_EXIST);
        }

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        customerInformationPanel = new javax.swing.JPanel();
        customerIdTextField = new javax.swing.JTextField();
        customerIdLabel = new javax.swing.JLabel();
        selectCustomerButton = new javax.swing.JButton();
        customerNameLabel = new javax.swing.JLabel();
        customerAddressLabel = new javax.swing.JLabel();
        customerAddressTextField = new javax.swing.JTextField();
        customerNameTextField = new javax.swing.JTextField();
        customerPhoneNumberLabel = new javax.swing.JLabel();
        customerPhoneNumberTextField = new javax.swing.JTextField();
        customerCityLabel = new javax.swing.JLabel();
        customerCityTextField = new javax.swing.JTextField();
        customerTypeLabel = new javax.swing.JLabel();
        customerTypeTextField = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        itemTable = new javax.swing.JTable();
        itemIdTextField = new javax.swing.JTextField();
        addItemButton = new javax.swing.JButton();
        removeItemTextField = new javax.swing.JButton();
        deliveryDateTextField = new javax.swing.JTextField();
        saveOrderButton = new javax.swing.JButton();
        deliveryStatusDropBox = new javax.swing.JComboBox();
        orderIdLabel = new javax.swing.JLabel();
        orderIdTextField = new javax.swing.JTextField();
        selectOrderButton = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        deliveryDateLabel = new javax.swing.JLabel();
        deliveryStatusLabel = new javax.swing.JLabel();
        dateFormatLabel = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        totalPriceTextField = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        customerInformationPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Customer information"));

        customerIdLabel.setText("ID:");

        selectCustomerButton.setText("Select customer");
        selectCustomerButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                selectCustomerButtonActionPerformed(evt);
            }
        });

        customerNameLabel.setText("Name:");

        customerAddressLabel.setText("Address:");

        customerAddressTextField.setEditable(false);

        customerNameTextField.setEditable(false);

        customerPhoneNumberLabel.setText("Phone number:");

        customerPhoneNumberTextField.setEditable(false);

        customerCityLabel.setText("City:");

        customerCityTextField.setEditable(false);

        customerTypeLabel.setText("Type:");

        customerTypeTextField.setEditable(false);

        javax.swing.GroupLayout customerInformationPanelLayout = new javax.swing.GroupLayout(customerInformationPanel);
        customerInformationPanel.setLayout(customerInformationPanelLayout);
        customerInformationPanelLayout.setHorizontalGroup(
            customerInformationPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(customerInformationPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(customerInformationPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(customerInformationPanelLayout.createSequentialGroup()
                        .addComponent(customerIdLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(customerIdTextField))
                    .addComponent(selectCustomerButton, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, Short.MAX_VALUE)
                .addGroup(customerInformationPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(customerAddressLabel, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(customerNameLabel, javax.swing.GroupLayout.Alignment.TRAILING))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(customerInformationPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, customerInformationPanelLayout.createSequentialGroup()
                        .addComponent(customerNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(customerCityLabel))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, customerInformationPanelLayout.createSequentialGroup()
                        .addComponent(customerAddressTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(customerPhoneNumberLabel)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(customerInformationPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(customerInformationPanelLayout.createSequentialGroup()
                        .addComponent(customerCityTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(customerTypeLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(customerTypeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(customerPhoneNumberTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(20, Short.MAX_VALUE))
        );
        customerInformationPanelLayout.setVerticalGroup(
            customerInformationPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(customerInformationPanelLayout.createSequentialGroup()
                .addGroup(customerInformationPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(customerIdLabel)
                    .addComponent(customerIdTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(customerNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(customerCityLabel)
                    .addComponent(customerCityTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(customerNameLabel)
                    .addComponent(customerTypeLabel)
                    .addComponent(customerTypeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(customerInformationPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(selectCustomerButton)
                    .addComponent(customerAddressTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(customerPhoneNumberLabel)
                    .addComponent(customerPhoneNumberTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(customerAddressLabel)))
        );

        itemTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Item ID", "Product name"
            }
        ));
        jScrollPane1.setViewportView(itemTable);

        addItemButton.setText("Add item");
        addItemButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addItemButtonActionPerformed(evt);
            }
        });

        removeItemTextField.setText("Remove item");
        removeItemTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeItemTextFieldActionPerformed(evt);
            }
        });

        saveOrderButton.setText("Save order");
        saveOrderButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveOrderButtonActionPerformed(evt);
            }
        });

        orderIdLabel.setText("Order ID:");

        selectOrderButton.setText("Select order");
        selectOrderButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                selectOrderButtonActionPerformed(evt);
            }
        });

        jLabel1.setText("Used for editing existing order");

        deliveryDateLabel.setText("Delivery date:");

        deliveryStatusLabel.setText("Delivery status:");

        dateFormatLabel.setText("Format: dd/MM/yyyy");

        jLabel2.setText("Item ID:");

        jLabel3.setText("Total price:");

        totalPriceTextField.setEditable(false);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(orderIdLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(orderIdTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(selectOrderButton))))
                    .addComponent(customerInformationPanel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(deliveryStatusLabel)
                                    .addComponent(deliveryDateLabel))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(deliveryStatusDropBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(deliveryDateTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 120, Short.MAX_VALUE)
                                    .addComponent(dateFormatLabel))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(totalPriceTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 83, Short.MAX_VALUE)
                                    .addComponent(saveOrderButton, javax.swing.GroupLayout.DEFAULT_SIZE, 85, Short.MAX_VALUE)))
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 347, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(removeItemTextField, 0, 0, Short.MAX_VALUE)
                            .addComponent(addItemButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel2)
                            .addComponent(itemIdTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 120, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 130, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(orderIdLabel)
                    .addComponent(orderIdTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(selectOrderButton))
                .addGap(3, 3, 3)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(customerInformationPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 174, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(deliveryStatusLabel)
                            .addComponent(deliveryStatusDropBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel3)
                            .addComponent(totalPriceTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(deliveryDateLabel)
                            .addComponent(deliveryDateTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(saveOrderButton))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(dateFormatLabel))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(itemIdTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(addItemButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(removeItemTextField)))
                .addContainerGap(22, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void selectOrderButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectOrderButtonActionPerformed
        if (!isEmpty(orderIdTextField)) {
            // Let's do something only if order ID is provided

            if (!orderSelected) {
                // If order is not selected - we select one
                try {
                    int orderId = Integer.parseInt(orderIdTextField.getText());

//                    order = returnDummySalesOrder();
                    System.out.println("Order id: " + orderId);
                    order = controller.getSalesOrder(orderId, true);
                    System.out.println("Order " + order.getStatus().getName());
                    fillOrderInformation(order);
                    orderSelected = true;
                    reactivateSelectCustomerButton(orderSelected);
                    reactivateSelectOrderButton(orderSelected);

                } catch (NumberFormatException ex) {
                    showDialog(ORDERID_TITLE, NOT_A_NUMBER);
                } catch (IllegalArgumentException ex) {
                    // Thrown by controller.getSalesOrder(...) when
                    // order with specified ID does not exist.
                    showDialog(ORDERID_TITLE, ORDER_DOES_NOT_EXIST);
                }
            } else {
                orderSelected = false;
                clearOrderInformation();
                reactivateSelectOrderButton(orderSelected);
            }
            calculateTotalPrice();
        } else {
            showDialog(ORDERID_TITLE, NOT_A_NUMBER);
        }
    }//GEN-LAST:event_selectOrderButtonActionPerformed

    private void reactivateSelectOrderButton(boolean enabled) {
        orderIdTextField.setEnabled(!enabled);
        selectOrderButton.setText(enabled ? DESELECT_ORDER : SELECT_ORDER);
    }

    private void reactivateSelectCustomerButton(boolean enabled) {
        customerIdTextField.setEnabled(!enabled);
        selectCustomerButton.setText(enabled ? DESELECT_CUSTOMER : SELECT_CUSTOMER);
    }

    private void selectCustomerButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectCustomerButtonActionPerformed
        if (!isEmpty(customerIdTextField)) {
            // Let's do something only if
            // customer ID is provided

            if (!customerSelected) {
                // If customer is not selected -
                // we select one
                try {
                    int customerId = Integer.parseInt(customerIdTextField.getText());


                    customer = controller.getCustomer(customerId, true);
//                    customer = returnDummyCustomer();

                    fillCustomerInformation(customer);
                    reactivateSelectCustomerButton(customerSelected);
                } catch (NumberFormatException ex) {
                    showDialog(CUSTOMERID_TITLE, NOT_A_NUMBER);
                } catch (IllegalArgumentException ex) {
                    // Exception thrown if
                    // customer with such ID
                    // does not exist.
                    showDialog(CUSTOMERID_TITLE, CUSTOMER_DOES_NOT_EXIST);
                }
            } else {
                // Deselect a customer - just clear all the customer data
                customerSelected = false;
                clearCustomerInformation();
                selectCustomerButton.setText(SELECT_CUSTOMER);
            }

        } else {
            showDialog(CUSTOMERID_TITLE, NOT_A_NUMBER);
        }
    }//GEN-LAST:event_selectCustomerButtonActionPerformed

    private void addItemButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addItemButtonActionPerformed
        if (!isEmpty(itemIdTextField)) {
            try {
                int itemId = Integer.parseInt(itemIdTextField.getText());

                Item i = controller.getItem(itemId, true);

                itemTableModel.addItem(i);
                itemTable.updateUI();
                calculateTotalPrice();
            } catch (NumberFormatException ex) {
                showDialog(ITEMID_TITLE, NOT_A_NUMBER);
            } catch (IllegalArgumentException ex) {
                showDialog(ITEMID_TITLE, ITEM_DOES_NOT_EXIST);
            }
        } else {
            showDialog(ITEMID_TITLE, NOT_A_NUMBER);
        }
    }//GEN-LAST:event_addItemButtonActionPerformed

    private void removeItemTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeItemTextFieldActionPerformed
        int selection;
        if ((selection = itemTable.getSelectedRow()) != -1) {
            // Means there is a selection
            itemTableModel.removeItem(selection);
            itemTable.clearSelection();
            itemTable.updateUI();
        } else {
            showDialog(ITEMID_TITLE, NO_ITEM_SELECTED);
        }
    }//GEN-LAST:event_removeItemTextFieldActionPerformed

    private Date getDeliveryDate() throws ParseException {
        return simpleDateFormat.parse(deliveryDateTextField.getText());
    }

    private Status getCurrentStatus() {
        return controller.getStatus(deliveryStatusDropBox.getSelectedItem().toString());
    }
    private void saveOrderButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveOrderButtonActionPerformed
        if (dataFilled()) {
            if (!orderSelected) {
                try {
                    order = new SalesOrder(0, new Date(), 0, itemTableModel.getItems(), getDeliveryDate(), customer, 0, 0, getCurrentStatus());
                    controller.createSalesOrder(order, true);
                } catch (ParseException ex) {
                    Logger.getLogger(OrderUI.class.getName()).log(Level.SEVERE, null, ex);
                }
            } else {
                try {
                    order.setCustomer(customer);
                    order.setItems(itemTableModel.getItems());
                    order.setDeliveryDate(getDeliveryDate());
                    order.setStatus(getCurrentStatus());
                    controller.updateSalesOrder(order, true);
                } catch (ParseException ex) {
                    Logger.getLogger(OrderUI.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            reactivateSelectCustomerButton(false);
            reactivateSelectOrderButton(false);
            clearOrderInformation();
            showDialog(null, ORDER_CREATED);
        } else {
            showDialog(null, ORDER_NOT_COMPLETE);
        }
    }//GEN-LAST:event_saveOrderButtonActionPerformed

    private boolean dataFilled() {
        boolean filled = true;
        filled &= customerSelected;
        filled &= itemTable.getRowCount() != 0;
        try {
            Date deliveryDate = simpleDateFormat.parse(deliveryDateTextField.getText());
        } catch (ParseException ex) {
            filled &= false;
        }
//        order.setStatus(controller.getStatus(deliveryStatusDropBox.getSelectedItem().toString()));

        return filled;
    }

    private void fillOrderInformation(SalesOrder order) {
        customer = order.getCustomer();
        items = order.getItems();
        itemTableModel = new ItemTableModel(items);
        itemTable.setModel(itemTableModel);

        Date delivery = order.getDeliveryDate();
        deliveryDateTextField.setText(simpleDateFormat.format(delivery));
        deliveryStatusDropBox.setSelectedItem(order.getStatus().getName());

        fillCustomerInformation(
                customer);


    }

    // Clears all the order data from the user interface
    private void clearOrderInformation() {
        order = null;
        orderIdTextField.setText(null);
        deliveryDateTextField.setText(null);

        clearItemsInformation();
        clearCustomerInformation();


    }

    private void clearItemsInformation() {
        itemTableModel.clear();
        itemTable.invalidate();


    }

    // Fills customer data in the text fields
    private void fillCustomerInformation(Customer customer) {
        customerIdTextField.setText("" + customer.getCustomerId());
        customerNameTextField.setText(customer.getName());
        customerPhoneNumberTextField.setText(customer.getPhoneNo());
        customerAddressTextField.setText(customer.getAddress());
        customerTypeTextField.setText(customer.getType().getName());
        customerCityTextField.setText(customer.getZipCode().getCity());
        customerSelected = true;


    }

    // Clears customer data from the text fields
    private void clearCustomerInformation() {
        customer = null;
        customerIdTextField.setText(null);
        customerNameTextField.setText(null);
        customerPhoneNumberTextField.setText(null);
        customerAddressTextField.setText(null);
        customerTypeTextField.setText(null);
        customerCityTextField.setText(null);
        customerIdTextField.setEnabled(true);
        customerSelected = false;


    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        try {
            // We just don't want the crappy Java look&feel
            // so let's use system default look&feel.
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());



        } catch (ClassNotFoundException ex) {
            Logger.getLogger(OrderUI.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            Logger.getLogger(OrderUI.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(OrderUI.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedLookAndFeelException ex) {
            Logger.getLogger(OrderUI.class.getName()).log(Level.SEVERE, null, ex);
        }
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new OrderUI().setVisible(true);


            }
        });


    } // Helper method to simplify code

    private boolean isEmpty(JTextField textField) {
        return textField.getText().equals(EMPTYSTRING);


    } // Another helper method to simplify code

    private void showDialog(String title, String message) {
        JOptionPane.showMessageDialog(this, message, title, JOptionPane.WARNING_MESSAGE);
    }

    private void calculateTotalPrice() {
        if (items != null) {
            if (items.size() > 0) {
                float total = 0;
                for (Item i : items) {
                    total += i.getProduct().getPrice();
                }
                totalPriceTextField.setText(String.valueOf(total));
            } else {
                totalPriceTextField.setText("0.0");
            }
        } else {
            totalPriceTextField.setText("0.0");
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addItemButton;
    private javax.swing.JLabel customerAddressLabel;
    private javax.swing.JTextField customerAddressTextField;
    private javax.swing.JLabel customerCityLabel;
    private javax.swing.JTextField customerCityTextField;
    private javax.swing.JLabel customerIdLabel;
    private javax.swing.JTextField customerIdTextField;
    private javax.swing.JPanel customerInformationPanel;
    private javax.swing.JLabel customerNameLabel;
    private javax.swing.JTextField customerNameTextField;
    private javax.swing.JLabel customerPhoneNumberLabel;
    private javax.swing.JTextField customerPhoneNumberTextField;
    private javax.swing.JLabel customerTypeLabel;
    private javax.swing.JTextField customerTypeTextField;
    private javax.swing.JLabel dateFormatLabel;
    private javax.swing.JLabel deliveryDateLabel;
    private javax.swing.JTextField deliveryDateTextField;
    private javax.swing.JComboBox deliveryStatusDropBox;
    private javax.swing.JLabel deliveryStatusLabel;
    private javax.swing.JTextField itemIdTextField;
    private javax.swing.JTable itemTable;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel orderIdLabel;
    private javax.swing.JTextField orderIdTextField;
    private javax.swing.JButton removeItemTextField;
    private javax.swing.JButton saveOrderButton;
    private javax.swing.JButton selectCustomerButton;
    private javax.swing.JButton selectOrderButton;
    private javax.swing.JTextField totalPriceTextField;
    // End of variables declaration//GEN-END:variables
}
